package org.wjk.controller;

import com.wf.captcha.SpecCaptcha;
import com.wf.captcha.utils.CaptchaUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.concurrent.ThreadPoolExecutor;

@RestController
@Slf4j
@RequiredArgsConstructor
public class CaptchaCtllr
{
    private final JedisPool jedisPool;
    private final ThreadPoolExecutor poolExecutor;
    @GetMapping("/captcha")
    public void getCatcha(HttpServletRequest request, HttpServletResponse response) throws IOException
    {
        //第一步：构造验证码 capTcha对象，设置验证码部分属性
        SpecCaptcha captcha=new SpecCaptcha(105,40,6);
        //第二步：获取验证码中验证信息
        String value=captcha.text().toLowerCase();
        log.debug("当前验证码信息是{}",value);
       //第三步：获取保存数据到redis中的key
        String key=request.getParameter("captchaKey");
        log.debug("当前验证码的key是{}",key);
        //最后一步：将验证码图片响应给前端
        CaptchaUtil.out(captcha,request,response);

        poolExecutor.execute(()->{
            Jedis jedis = jedisPool.getResource();
            String res = jedis.setex(key,180L,value);
            log.debug("保存当前验证码到redis中，其中key为{}，value为{}，操作结果为{}",key,value,res);
        });
    }
}
